package leetcode.offer_two_special.linked;

import java.util.Stack;

/**
 * @author mazouri
 * @create 2021-09-06 23:34
 */
public class _25_addTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();

        while (l1 != null) {
            s1.push(l1.val);
            l1 = l1.next;
        }

        while (l2 != null) {
            s2.push(l2.val);
            l2 = l2.next;
        }
        //进位
        int carry = 0, val1 = 0, val2 = 0, sum = 0;
        ListNode head = null;
        while (!s1.isEmpty() || !s2.isEmpty() || carry == 1) {
            val1 = s1.isEmpty() ? 0 : s1.pop();
            val2 = s2.isEmpty() ? 0 : s2.pop();

            sum = val1 + val2 + carry;
            carry = sum / 10;

            ListNode cur = new ListNode(sum % 10);
            cur.next = head;
            head = cur;
        }

        return head;
    }
}
